<?php

/**
 * 夏日葵电商系统
 * http://www.xiarikui.com
 */

namespace Admin\Controller;

use Admin\Model\GoodsModel;
use Think\AjaxPage;
use Think\Page;

class GoodsController extends BaseController {

    /**
     *  商品分类列表
     */
    public function categoryList() {
        $GoodsModel = new GoodsModel();
        $goodsCatRs = $GoodsModel->goodsCatList();
        $this->assign('cat_list', $goodsCatRs);
        $this->display();
    }

    /**
     * 添加修改商品分类
     * 手动拷贝分类正则 ([\u4e00-\u9fa5/\w]+)  ('393','$1'), 
     */
    public function addEditCategory() {
        $GoodsModel = new GoodsModel();
        if (IS_GET) {
            $goodsCatInfo = D('goodsCat')->where('id=' . I('GET.id', 0))->find();
            $level_cat = $GoodsModel->find_parent_cat($goodsCatInfo['id']); // 获取分类默认选中的下拉框
            $cat_list = M('goods_cat')->where("parent_id = 0")->select();
            $this->assign('level_cat', $level_cat);
            $this->assign('cat_list', $cat_list);
            $this->assign('goods_cat_info', $goodsCatInfo);
            $this->display('_category');
            exit;
        }

        $goodsCat = D('goodsCat');
        $type = $_POST['id'] > 0 ? 2 : 1; // 标识自动验证时的 场景 1 表示插入 2 表示更新                        
        if ($_GET['is_ajax'] == 1) {
            C('TOKEN_ON', false);
            if (!$goodsCat->create(NULL, $type)) {
                $returnArr = array(
                    'status' => -1,
                    'msg' => '操作失败!',
                    'data' => $goodsCat->getError(),
                );
                $this->ajaxReturn(json_encode($returnArr));
            } else {
                C('TOKEN_ON', true);
                $goodsCat->parent_id = $_POST['parent_id_1'];
                $_POST['parent_id_2'] && ($goodsCat->parent_id = $_POST['parent_id_2']);

                if ($goodsCat->id > 0 && $goodsCat->parent_id == $goodsCat->id) {
                    $returnArr = array(
                        'status' => -1,
                        'msg' => '上级分类不能为自己',
                        'data' => '',
                    );
                    $this->ajaxReturn(json_encode($returnArr));
                }
//                if ($goodsCat->commission_rate > 100) {
//                    $returnArr = array(
//                        'status' => -1,
//                        'msg' => '分佣比例不得超过100%',
//                        'data' => '',
//                    );
//                    $this->ajaxReturn(json_encode($returnArr));
//                }
                if ($type == 2) {
                    $goodsCat->save();
                    $GoodsModel->refreshCat($_POST['id']);
                } else {
                    $id = $goodsCat->add();
                    $GoodsModel->refreshCat($id);
                }
                $returnArr = array(
                    'status' => 1,
                    'msg' => '操作成功',
                    'data' => array('url' => U('Admin/Goods/categoryList')),
                );
                $this->ajaxReturn(json_encode($returnArr));
            }
        }
    }

    /**
     * 获取商品分类
     */
    public function ajaxGetSpecList() {
        $GoodsModel = new GoodsModel();
        $_REQUEST['category_id'] = $_REQUEST['category_id'] ? $_REQUEST['category_id'] : 0;
        $filterSpec = M('goodsCat')->where("id = " . $_REQUEST['category_id'])->getField('filter_spec');
        $filterSpecArr = explode(',', $filterSpec);
        $str = $GoodsModel->GetSpecCheckboxList($_REQUEST['type_id'], $filterSpecArr);
        $str = $str ? $str : '没有可帅选的商品规格';
        exit($str);
    }

    /**
     * 获取商品属性
     */
    public function ajaxGetAttrList() {
        $GoodsModel = new GoodsModel();
        $_REQUEST['category_id'] = $_REQUEST['category_id'] ? $_REQUEST['category_id'] : 0;
        $filterAttr = M('goodsCat')->where("id = " . $_REQUEST['category_id'])->getField('filter_attr');
        $filterAttrArr = explode(',', $filterAttr);
        $str = $GoodsModel->GetAttrCheckboxList($_REQUEST['type_id'], $filterAttrArr);
        $str = $str ? $str : '没有可帅选的商品属性';
        exit($str);
    }

    /**
     * 删除分类
     */
    public function delgoodsCat() {
        $goodsCat = M("goodsCat");
        $count = $goodsCat->where("parent_id = {$_GET['id']}")->count("id");
        $count > 0 && $this->error('该分类下还有分类不得删除!', U('Admin/Goods/categoryList'));
        $count = M('Goods')->where("cat_id = {$_GET['id']}")->count('1');
        $count > 0 && $this->error('该分类下有商品不得删除!', U('Admin/Goods/categoryList'));
        $goodsCat->where("id = {$_GET['id']}")->delete();
        $this->success("操作成功!!!", U('Admin/Goods/categoryList'));
    }

    /**
     *  商品列表
     */
    public function goodsList() {
        $GoodsModel = new GoodsModel();
        $brandRs = $GoodsModel->getSortBrands();
//        $categoryList = $GoodsModel->getSortCategory();
        $cate = M("goodsCat")->select();
        $cate = convert_arr_key($cate, 'id');
        $arr = [];
        foreach ($cate as $item => $value) {
            $arr[] = $value;
            foreach ($arr as $it => $val) {
                if ($val['id'] == $value['parent_id']) {
                    $n = array_search($arr[$it], $arr);
                    array_splice($arr, $n + 1, 0, [$value]);
                    array_pop($arr);
                    break;
                }
            }
        }
        $cate = $arr;
        $str = '　　';
        foreach ($cate as $item => $value) {
            switch ($value['level']) {
                case 1:
                    $cate[$item]['name'] = '|-' . $value['name'];
                    $cate[$item]['mobile_name'] = '|-' . $value['mobile_name'];
                    break;
                case 2:
                    $cate[$item]['name'] = $str . '|-' . $value['name'];
                    $cate[$item]['mobile_name'] = $str . '|-' . $value['mobile_name'];
                    break;
                case 3:
                    $cate[$item]['name'] = $str . $str . '|-' . $value['name'];
                    $cate[$item]['mobile_name'] = $str . $str . '|-' . $value['mobile_name'];
                    break;
            }
        }
        $this->assign('categoryList', $cate);
        $this->assign('brandList', $brandRs);
        $this->display();
    }

    /**
     *  获取商品数据
     */
    public function ajaxGoodsList() {
        $where = ' 1 = 1 ';
        I('intro') && $where = "$where and " . I('intro') . " = 1";
        I('brand_id') && $where = "$where and brand_id = " . I('brand_id');
        (I('is_on_sale') !== '') && $where = "$where and is_on_sale = " . I('is_on_sale');
        $catId = I('cat_id');
        $keyword = I('key_word') ? trim(I('key_word')) : '';
        if ($keyword) {
            $where = "$where and (goods_name like '%$keyword%' or goods_sn like '%$keyword%')";
        }
        if ($catId > 0) {
            $grandsonIds = getGoodsSubCat($catId);
            $where .= " and cat_id in(" . implode(',', $grandsonIds) . ") "; // 初始化搜索条件
        }
        $model = M('Goods');
        $count = $model->where($where)->count();
        $Page = new AjaxPage($count, 10);
        /**  搜索条件下 分页赋值
          foreach($condition as $key=>$val) {
          $Page->parameter[$key]   =   urlencode($val);
          }
         */
        $show = $Page->show();
        $order_str = " goods_id desc";
//        $order_str = "`{$_POST['orderby1']}` {$_POST['orderby2']}";
        $goodsRs = $model->where($where)->order($order_str)->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $catRs = D('goods_cat')->select();
        $catRs = convert_arr_key($catRs, 'id');
        $this->assign('catList', $catRs);
        $this->assign('goodsList', $goodsRs);
        $this->assign('page', $show);
        $this->display();
    }

    /**
     * 商品增改
     */
    public function addEditGoods() {
        $GoodsModel = new GoodsModel();
        $Goods = D('Goods'); //
        $type = $_POST['goods_id'] > 0 ? 2 : 1; // 标识自动验证时的 场景 1 表示插入 2 表示更新                        
        if (($_GET['is_ajax'] == 1) && IS_POST) {
            C('TOKEN_ON', false);
            $shippingAreaIds = I('shipping_area_ids');
            $returnArr = array(
                'status' => -1,
                'msg' => '请选择物流!',
                'data' => $Goods->getError(),
            );
            if ($_POST['weight'] == 0 || strlen($_POST['weight']) === 0 || !is_numeric($_POST['weight'])) {
                $returnArr['msg'] = '商品重量不能为0';
                $this->ajaxReturn(json_encode($returnArr));
            }

            if (empty($shippingAreaIds)) {
                $this->ajaxReturn(json_encode($returnArr));
            }
            if (!$Goods->create(NULL, $type)) {
                $returnArr['msg'] = '操作失败';
                $this->ajaxReturn(json_encode($returnArr));
            } else {
                $Goods->on_time = time(); // 上架时间
                //$Goods->cat_id = $_POST['cat_id_1'];
                $_POST['cat_id_2'] && ($Goods->cat_id = $_POST['cat_id_2']);
                $_POST['cat_id_3'] && ($Goods->cat_id = $_POST['cat_id_3']);
                $_POST['extend_cat_id_2'] && ($Goods->extend_cat_id = $_POST['extend_cat_id_2']);
                $_POST['extend_cat_id_3'] && ($Goods->extend_cat_id = $_POST['extend_cat_id_3']);
                $ids = [];
                $shippingIds = [];
                foreach ($shippingAreaIds as $item => $value) {
                    $shippingIds[] = $item;
                    foreach ($value as $k => $v) {
                        $ids[] = $v;
                    }
                }

                $Goods->shipping_area_ids = implode(',', $shippingAreaIds);
//                $Goods->shipping_code = implode(',', $shippingIds);
                if ($type == 2) {
                    $goodsId = $_POST['goods_id'];
                    $Goods->save();
                    M('cart')->where("goods_id = $goodsId and spec_key = ''")->save(array(
                        'market_price' => $_POST['market_price'], //市场价
                        'goods_price' => $_POST['shop_price'], // 本店价
                        'member_goods_price' => $_POST['shop_price'], // 会员折扣价                        
                    ));
                    $Goods->afterSave($goodsId);
                } else {
                    $goodsId = $id = $Goods->add();
                    $Goods->afterSave($goodsId);
                }
                $GoodsModel->saveGoodsAttr($goodsId, $_POST['goods_type']); // 处理商品 属性
                $returnArr = array(
                    'status' => 1,
                    'msg' => '操作成功',
                    'data' => array('url' => U('Admin/Goods/goodsList/p/' . $_REQUEST['p'])),
                );
                $this->ajaxReturn(json_encode($returnArr));
            }
        }
        $goodsInfo = D('Goods')->where('goods_id=' . I('GET.id', 0))->find();
        //$goodsCatRs = $GoodsModel->goodsCatList();
        $levelCat = $GoodsModel->find_parent_cat($goodsInfo['cat_id']); // 获取分类默认选中的下拉框
        $levelCat2 = $GoodsModel->find_parent_cat($goodsInfo['extend_cat_id']); // 获取分类默认选中的下拉框
        $goodsCatRs = M('goods_cat')->where("parent_id = 0")->select();
        $brandRs = $GoodsModel->getSortBrands();
        $goodsType = M("GoodsType")->select();
        $suppliersRs = M("supplier")->select();
        $pluginShipping = M('plugin')->where(array('type' => array('eq', 'shipping'), 'status' => 1))->select(); //插件物流
        $shippingArea = D('shipping_area')->getShippingArea(); //配送区域
        $goodsShippingAreaIds = explode(',', $goodsInfo['shipping_area_ids']);
        $this->assign('goods_shipping_area_ids', $goodsShippingAreaIds);
        $this->assign('shipping_area', $shippingArea);
        $this->assign('pluginShipping', $pluginShipping);
        $this->assign('suppliersList', $suppliersRs);
        $this->assign('level_cat', $levelCat);
        $this->assign('level_cat2', $levelCat2);
        $this->assign('cat_list', $goodsCatRs);
        $this->assign('brandList', $brandRs);
        $this->assign('goodsType', $goodsType);
        $this->assign('goodsInfo', $goodsInfo);
        $goodsImg = M("goodsImg")->where('goods_id =' . I('GET.id', 0))->select();
        $this->assign('goodsImg', $goodsImg);
        $this->initEditor();
        $this->display('_goods');
    }

    /**
     * 商品类型
     */
    public function goodsTypeList() {
        $model = M("GoodsType");
        $count = $model->count();
        $Page = new Page($count, 100);
        $show = $Page->show();
        $goodsTypeRs = $model->order("id desc")->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $this->assign('show', $show);
        $this->assign('goodsTypeList', $goodsTypeRs);
        $this->display('goodsTypeList');
    }

    /**
     * 商品类型增改
     */
    public function addEditGoodsType() {
        $_GET['id'] = $_GET['id'] ? $_GET['id'] : 0;
        $model = M("GoodsType");
        if (IS_POST) {
            $model->create();
            if ($_GET['id']) {
                $model->save();
            } else {
                $model->add();
            }
            $this->success("操作成功!!!", U('Admin/Goods/goodsTypeList'));
            exit;
        }
        $goodsType = $model->find($_GET['id']);
        $this->assign('goodsType', $goodsType);
        $this->display('_goodsType');
    }

    /**
     * 商品属性
     */
    public function goodsAttrList() {
        $goodsTypeRs = M("GoodsType")->select();
        $this->assign('goodsTypeList', $goodsTypeRs);
        $this->display();
    }

    /**
     *  获取商品属性数据
     */
    public function ajaxGoodsAttrList() {
        $where = ' 1 = 1 ';
        I('type_id') && $where = "$where and type_id = " . I('type_id');
        $model = M('GoodsAttr');
        $count = $model->where($where)->count();
        $Page = new AjaxPage($count, 13);
        $show = $Page->show();
        $goodsAttrRs = $model->where($where)->order('`order` desc,attr_id DESC')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $goodsTypeRs = M("GoodsType")->getField('id,name');
        $attrInpType = array(0 => '手工录入', 1 => ' 从列表中选择', 2 => ' 多行文本框');
        $this->assign('attr_input_type', $attrInpType);
        $this->assign('goodsTypeList', $goodsTypeRs);
        $this->assign('goodsAttrList', $goodsAttrRs);
        $this->assign('page', $show);
        $this->display();
    }

    /**
     * 商品属性增删改
     */
    public function addEditGoodsAttr() {
        $model = D("GoodsAttr");
        $type = $_POST['attr_id'] > 0 ? 2 : 1; // 标识自动验证时的 场景 1 表示插入 2 表示更新         
        $_POST['attr_values'] = str_replace('_', '', $_POST['attr_values']);
        $_POST['attr_values'] = str_replace('@', '', $_POST['attr_values']);
        $_POST['attr_values'] = trim($_POST['attr_values']);
        if (($_GET['is_ajax'] == 1) && IS_POST) {
            C('TOKEN_ON', false);
            if (!$model->create(NULL, $type)) {
                $returnArr = array(
                    'status' => -1,
                    'msg' => '提交不成功!',
                    'data' => $model->getError(),
                );
                $this->ajaxReturn(json_encode($returnArr));
            } else {
                // C('TOKEN_ON',true); 
                if ($type == 2) {
                    $model->save();
                } else {
                    $id = $model->add();
                }
                $returnArr = array(
                    'status' => 1,
                    'msg' => '操作成功',
                    'data' => array('url' => U('Admin/Goods/goodsAttrList')),
                );
                $this->ajaxReturn(json_encode($returnArr));
            }
        }
        $_GET['attr_id'] = $_GET['attr_id'] ? $_GET['attr_id'] : 0;
        $goodsTypeRs = M("GoodsType")->select();
        $goodsAttr = $model->find($_GET['attr_id']);
        $this->assign('goodsTypeList', $goodsTypeRs);
        $this->assign('goodsAttr', $goodsAttr);
        $this->display('_goodsAttr');
    }

    /**
     * 更改指定表的指定字段
     */
    public function updateField() {
        $primary = array(
            'goods' => 'goods_id',
            'goods_cat' => 'id',
            'brand' => 'id',
            'goods_attr' => 'attr_id',
            'ad' => 'ad_id',
        );
        $model = D($_POST['table']);
        $model->$primary[$_POST['table']] = $_POST['id'];
        $model->$_POST['field'] = $_POST['value'];
        $model->save();
        $returnArr = array(
            'status' => 1,
            'msg' => '操作成功',
            'data' => array('url' => U('Admin/Goods/goodsAttrList')),
        );
        $this->ajaxReturn(json_encode($returnArr));
    }

    /**
     * 获取商品属性
     */
    public function ajaxGetAttrInput() {
        $GoodsModel = new GoodsModel();
        $str = $GoodsModel->getAttrInput($_REQUEST['goods_id'], $_REQUEST['type_id']);
        exit($str);
    }

    /**
     * 删除商品
     */
    public function delGoods() {
        $goodsId = $_GET['id'];
        $error = '';
        // 判断此商品是否有订单
        $c1 = M('OrderGoods')->where("goods_id = $goodsId")->count('1');
        $c1 && $error .= '此商品有订单,不得删除! <br/>';

        // 商品团购
        $c1 = M('goods_groupon')->where("goods_id = $goodsId")->count('1');
        $c1 && $error .= "此商品有团购,不得删除! <br/>";

        // 商品退货记录
        $c1 = M('order_return')->where("goods_id = $goodsId")->count('1');
        $c1 && $error .= '此商品有退货记录,不得删除! <br/>';

        if ($error) {
            $returnArr = array('status' => -1, 'msg' => $error, 'data' => '',);   //$returnArr = array('status' => -1,'msg' => '删除失败','data'  =>'',);
            $this->ajaxReturn(json_encode($returnArr));
        }

        // 删除此商品        
        M("Goods")->where('goods_id =' . $goodsId)->delete();  //商品表
        M("cart")->where('goods_id =' . $goodsId)->delete();  // 购物车
        M("comment")->where('goods_id =' . $goodsId)->delete();  //商品评论
        M("goods_consult")->where('goods_id =' . $goodsId)->delete();  //商品咨询
        M("goods_img")->where('goods_id =' . $goodsId)->delete();  //商品相册
        M("goods_stock")->where('goods_id =' . $goodsId)->delete();  //商品规格
        M("spec_img")->where('goods_id =' . $goodsId)->delete();  //商品规格图片
        M("goods_to_attr")->where('goods_id =' . $goodsId)->delete();  //商品属性
        M("goods_collect")->where('goods_id =' . $goodsId)->delete();  //商品收藏

        $returnArr = array('status' => 1, 'msg' => '操作成功', 'data' => '',);   //$returnArr = array('status' => -1,'msg' => '删除失败','data'  =>'',);
        $this->ajaxReturn(json_encode($returnArr));
    }

    /**
     * 删除商品类型 
     */
    public function delGoodsType() {
        $count = M("Spec")->where("type_id = {$_GET['id']}")->count("1");
        $count > 0 && $this->error('该类型下有商品规格不得删除!', U('Admin/Goods/goodsTypeList'));
        $count = M("GoodsAttr")->where("type_id = {$_GET['id']}")->count("1");
        $count > 0 && $this->error('该类型下有商品属性不得删除!', U('Admin/Goods/goodsTypeList'));
        M('GoodsType')->where("id = {$_GET['id']}")->delete();
        $this->success("操作成功!!!", U('Admin/Goods/goodsTypeList'));
    }

    /**
     * 删除商品属性
     */
    public function delGoodsAttr() {
        $count = M("GoodsToAttr")->where("attr_id = {$_GET['id']}")->count("1");
        $count > 0 && $this->error('有商品使用该属性,不得删除!', U('Admin/Goods/goodsAttrList'));
        M('GoodsAttr')->where("attr_id = {$_GET['id']}")->delete();
        $this->success("操作成功!!!", U('Admin/Goods/goodsAttrList'));
    }

    /**
     * 删除商品规格
     */
    public function delGoodsSpec() {
        $count = M("SpecItem")->where("spec_id = {$_GET['id']}")->count("1");
        $count > 0 && $this->error('清空规格项后才可以删除!', U('Admin/Goods/specList'));
        M('Spec')->where("id = {$_GET['id']}")->delete();
        $this->success("操作成功!!!", U('Admin/Goods/specList'));
    }

    /**
     * 品牌列表
     */
    public function brandList() {
        $model = M("Brand");
        $keyword = I('keyword');
        $where = $keyword ? " name like '%$keyword%' " : "";
        $count = $model->where($where)->count();
        $Page = new Page($count, 10);
        $brandRs = $model->where($where)->order("`sort` asc")->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $show = $Page->show();
        $goodsCatRs = M('goods_cat')->where("parent_id = 0")->getField('id,name');
        $this->assign('cat_list', $goodsCatRs);
        $this->assign('show', $show);
        $this->assign('brandList', $brandRs);
        $this->display('brandList');
    }

    /**
     * 商品品牌增改
     */
    public function addEditBrand() {
        $id = I('id');
        $model = M("Brand");
        if (IS_POST) {
            $model->create();
            if ($id) {
                $model->save();
            } else {
                $id = $model->add();
            }
            $this->success("操作成功!!!", U('Admin/Goods/brandList', array('p' => $_GET['p'])));
            exit;
        }
        $goodsCatRs = M('goods_cat')->where("parent_id = 0")->select();
        $this->assign('cat_list', $goodsCatRs);
        $brand = $model->find($id);
        $this->assign('brand', $brand);
        $this->display('_brand');
    }

    /**
     * 删除品牌
     */
    public function delBrand() {
        $count = M('Goods')->where("brand_id = {$_GET['id']}")->count('1');
        if ($count) {
            $returnArr = array('status' => -1, 'msg' => '此品牌有商品在用不得删除!', 'data' => '',);   //$returnArr = array('status' => -1,'msg' => '删除失败','data'  =>'',);
            $this->ajaxReturn(json_encode($returnArr));
        }
        $model = M("Brand");
        $model->where('id =' . $_GET['id'])->delete();
        $returnArr = array('status' => 1, 'msg' => '操作成功', 'data' => '',);   //$returnArr = array('status' => -1,'msg' => '删除失败','data'  =>'',);
        $this->ajaxReturn(json_encode($returnArr));
    }

    /**
     * 初始化编辑器链接     
     */
    private function initEditor() {
        $this->assign("URL_upload", U('Admin/Ueditor/imageUp', array('savepath' => 'goods'))); // 图片上传目录
        $this->assign("URL_imageUp", U('Admin/Ueditor/imageUp', array('savepath' => 'article'))); //  不知道啥图片
        $this->assign("URL_fileUp", U('Admin/Ueditor/fileUp', array('savepath' => 'article'))); // 文件上传s
        $this->assign("URL_scrawlUp", U('Admin/Ueditor/scrawlUp', array('savepath' => 'article')));  //  图片流
        $this->assign("URL_getRemoteImage", U('Admin/Ueditor/getRemoteImage', array('savepath' => 'article'))); // 远程图片管理
        $this->assign("URL_imageManager", U('Admin/Ueditor/imageManager', array('savepath' => 'article'))); // 图片管理        
        $this->assign("URL_getMovie", U('Admin/Ueditor/getMovie', array('savepath' => 'article'))); // 视频上传
        $this->assign("URL_Home", "");
    }

    /**
     * 商品规格列表    
     */
    public function specList() {
        $goodsTypeRs = M("GoodsType")->select();
        $this->assign('goodsTypeList', $goodsTypeRs);
        $this->display();
    }

    /**
     *  商品规格数据
     */
    public function ajaxSpecList() {
        $where = ' 1 = 1 ';
        I('type_id') && $where = "$where and type_id = " . I('type_id');
        $model = D('spec');
        $count = $model->where($where)->count();
        $Page = new AjaxPage($count, 13);
        $show = $Page->show();
        $specRs = $model->where($where)->order('id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $GoodsModel = new GoodsModel();
        foreach ($specRs as $k => $v) {
            $arr = $GoodsModel->getSpecItem($v['id']);
            $specRs[$k]['spec_item'] = implode(' , ', $arr);
        }

        $this->assign('specList', $specRs);
        $this->assign('page', $show);
        $goodsTypeRs = M("GoodsType")->select();
        $goodsTypeRs = convert_arr_key($goodsTypeRs, 'id');
        $this->assign('goodsTypeList', $goodsTypeRs);
        $this->display();
    }

    /**
     * 商品规格增改
     */
    public function addEditSpec() {
        $model = D("spec");
        $type = $_POST['id'] > 0 ? 2 : 1; // 标识自动验证时的 场景 1 表示插入 2 表示更新             
        if (($_GET['is_ajax'] == 1) && IS_POST) {
            C('TOKEN_ON', false);
            if (!$model->create(NULL, $type)) {
                $returnArr = array(
                    'status' => -1,
                    'msg' => $model->getError(),
//                    'data' => $model->getError(),
                );
                $this->ajaxReturn(json_encode($returnArr));
            } else {
                $specArr = $model->where('type_id = ' . $_POST['type_id'])->getField('type_id,name');
                $result = array_search($_POST['name'], $specArr, true);

                if ($type == 2) {
                    if ($result && $result != $_POST['type_id']) {
                        $returnArr = array(
                            'status' => -1,
                            'msg' => '规格名字已存在',
                        );
                        $this->ajaxReturn(json_encode($returnArr));
                        die();
                    }
                    $model->save();
                    $model->afterSave($_POST['id']);
                } else {
                    if ($result) {
                        $returnArr = array(
                            'status' => -1,
                            'msg' => '规格名字已存在',
                        );
                        $this->ajaxReturn(json_encode($returnArr));
                        die();
                    }
                    $id = $model->add();
                    $model->afterSave($id);
                }
                $returnArr = array(
                    'status' => 1,
                    'msg' => '操作成功',
                    'data' => array('url' => U('Admin/Goods/specList')),
                );
                $this->ajaxReturn(json_encode($returnArr));
            }
        }

        $id = $_GET['id'] ? $_GET['id'] : 0;
        $spec = $model->find($id);
        $GoodsModel = new GoodsModel();
        $items = $GoodsModel->getSpecItem($id);
        $spec[items] = implode(PHP_EOL, $items);
        $this->assign('spec', $spec);

        $goodsTypeRs = M("GoodsType")->select();
        $this->assign('goodsTypeList', $goodsTypeRs);
        $this->display('_spec');
    }

    /**
     * 获取商品规格选择框
     */
    public function ajaxGetSpecSelect() {
        $goodsId = $_GET['goods_id'] ? $_GET['goods_id'] : 0;
        $specRs = D('Spec')->where("type_id = " . $_GET['spec_type'])->order('`order` desc')->select();
        foreach ($specRs as $k => $v) {
            $specRs[$k]['spec_item'] = D('SpecItem')->where("spec_id = " . $v['id'])->order('id')->getField('id,item');
        }
        $itemsId = M('GoodsStock')->where('goods_id = ' . $goodsId)->getField("GROUP_CONCAT(`key` SEPARATOR '_') AS items_id");
        $itemsIds = explode('_', $itemsId);
        if ($goodsId) {
            $specImageRs = M('SpecImg')->where("goods_id = $goodsId")->getField('spec_img_id,src');
        }
        $this->assign('specImageList', $specImageRs);
        $this->assign('items_ids', $itemsIds);
        $this->assign('specList', $specRs);
        $this->display('ajax_spec_select');
    }

    /**
     * 获取商品规格输入框
     */
    public function ajaxGetSpecInput() {
        $GoodsModel = new GoodsModel();
        $goodsId = $_REQUEST['goods_id'] ? $_REQUEST['goods_id'] : 0;
        $str = $GoodsModel->getSpecInput($goodsId, $_POST['spec_arr']);
        exit($str);
    }

    /**
     * 删除商品相册图
     */
    public function delGoodsImg() {
        $path = I('filename', '');
        M('goods_img')->where("image_url = '$path'")->delete();
    }

}
